package com.rural.bus.driver;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.navisdk.adapter.BaiduNaviManager.NaviInitListener;
import com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rural.bus.driver.config.BusConstant;
import com.rural.bus.driver.config.MyPreferenceManager;
import com.rural.bus.driver.config.PreferenceKey;
import com.rural.bus.driver.fragment.MyOrderFragment;
import com.rural.bus.driver.model.Order;
import com.rural.bus.driver.net.MyHttpUtil;
import com.rural.bus.driver.net.OnNetCallback;
import com.rural.bus.driver.net.Url;
import com.rural.bus.driver.service.DistanceService;
import com.rural.bus.driver.utils.CommonTools;
import com.rural.bus.driver.utils.DateUtil;
import com.rural.bus.driver.utils.FileUtils;
import com.rural.bus.driver.utils.MyLocationClient;
import com.rural.bus.driver.utils.ProgressUtil;
import com.rural.bus.driver.utils.ToastUtil;
import com.rural.bus.driver.view.CircleImageView;
import com.rural.bus.driver.view.CommonAlertDialog;

public class OrderDetailActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = OrderDetailActivity.class.getSimpleName();
	private static final String APP_FOLDER_NAME = "Ruralbus_driver";
	private static final int SET_NAVIGATION_DISTANCE = 0x90;

	public static final String ROUTE_PLAN_NODE = "routePlanNode";

	private Button btn_order_operation;
	private CircleImageView iv_passenger_head;
	private ImageView iv_call;
	private LinearLayout ll_passenger_message,ll_navigation_distance;
	private TextView tv_passenger_name, tv_order_type, tv_start_time, tv_start_location, tv_end_location, tv_passenger_message, tv_navigation_distance, tv_passenger_phone;
	private double navigateDistance;

	CommonAlertDialog dialog1, dialog2, dialog3;

	private Order order;
	private int order_id;
	private String mSDCardPath = null;
	public static List<Activity> activityList = new LinkedList<Activity>();
	public double preLatitude;
	public double preLongitude;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SET_NAVIGATION_DISTANCE:
				int distance = msg.arg1;
				if (tv_navigation_distance != null) {
					tv_navigation_distance.setText("全程约 " + distance + " 公里");
					MyPreferenceManager.instance().putSharedInfoOfFloat(PreferenceKey.GO_DISTANCE, distance);
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activityList.add(this);
		setContentView(R.layout.activity_order_detail);

	}

	@Override
	protected void initView() {
		mBtMiddle.setText("订单详情");
		mBtMiddle.setVisibility(View.VISIBLE);
		mBtMiddle.setTextColor(getResources().getColor(R.color.white));

		mImgLeft.setVisibility(View.VISIBLE);
		mImgLeft.setBackgroundResource(R.drawable.back_bg_selector);

		btn_order_operation = (Button) findViewById(R.id.btn_order_operation);
		iv_passenger_head = (CircleImageView) findViewById(R.id.iv_passenger_head);
		tv_passenger_name = (TextView) findViewById(R.id.tv_passenger_name);
		tv_order_type = (TextView) findViewById(R.id.tv_order_type);
		tv_start_time = (TextView) findViewById(R.id.tv_start_time);
		tv_start_location = (TextView) findViewById(R.id.tv_start_location);
		tv_end_location = (TextView) findViewById(R.id.tv_end_location);
		tv_passenger_message = (TextView) findViewById(R.id.tv_passenger_message);
		tv_navigation_distance = (TextView) findViewById(R.id.tv_navigation_distance);
		tv_passenger_phone = (TextView) findViewById(R.id.tv_passenger_phone);
		iv_call = (ImageView) findViewById(R.id.iv_call);
		
		ll_passenger_message = (LinearLayout) findViewById(R.id.ll_passenger_message);
		ll_navigation_distance = (LinearLayout) findViewById(R.id.ll_navigation_distance);

	}

	@Override
	public void initData() {
		order_id = getIntent().getIntExtra("order_id", 0);
		if (0 == order_id) {
			toast("订单异常，请刷新列表重试");
			this.finish();
			return;
		}

		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("orderId", "" + order_id);
		ProgressUtil.showProgress(this, "");
		http.send(Url.orderdetail_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				ProgressUtil.closeProgress();

				try {
					if (object.get("status").equals("0")) {
						object = object.getJSONObject("result");
						if (object != null) {
							Log.d("rural", object.toString());
							order = new Gson().fromJson(object.toString(), new TypeToken<Order>() {
							}.getType());
							if (order != null) {
								fillViewWithData(order);
							}
						}
					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
			}
		});
	}

	private void fillViewWithData(Order order) {
		tv_passenger_name.setText("" + order.userName);
		tv_start_time.setText("" + DateUtil.formatDiscriptionTime(order.takeTime));
		tv_start_location.setText("" + order.startLocation);
		tv_end_location.setText("" + order.endLocation);
		if (!CommonTools.isEmpty(order.remarks)) {
			ll_passenger_message.setVisibility(View.VISIBLE);
			tv_passenger_message.setText("" + order.remarks);
		}else{
			ll_passenger_message.setVisibility(View.GONE);
		}
		if (!CommonTools.isEmpty(order.userPhone)) {
			tv_passenger_phone.setText("(" + order.userPhone + ")");
		}
		// STATUS0("新订单", 0),STATUS1("已接单", 1), STATUS2("已就绪", 2),
		// STATUS3("已出发", 3),STATUS4("已取消", 4),STATUS5("已结束", 5), STATUS6("完成",
		// 6), STATUS7("异常 ",7);
		mBtRight.setVisibility(View.INVISIBLE);
		ll_navigation_distance.setVisibility(View.VISIBLE);
		switch (order.orderStatus) {
		case 1:
			btn_order_operation.setText("我已就位");
			break;
		case 2:
			btn_order_operation.setText("出发");
			break;
		case 3:
			if (order.orderType != 4) {
				mBtRight.setVisibility(View.VISIBLE);
				mBtRight.setText("导航到目的地");
				mBtRight.setOnClickListener(this);
			}
			btn_order_operation.setText("已到目的地");
			break;
		case 4:
			btn_order_operation.setText("已取消");
			break;
		case 5:
			btn_order_operation.setText("去结算");
			break;
		default:
			btn_order_operation.setText("状态异常");
			break;
		}
		// TYPE0("马上用车", 0),TYPE1("预约用车", 1), TYPE3("全天租", 3), TYPE4("拼车", 4);
		switch (order.orderType) {
		case 0:
			tv_order_type.setText("马上用车");
			break;
		case 1:
			tv_order_type.setText("预约用车");
			break;
		case 3:
			tv_order_type.setText("日租");
			ll_navigation_distance.setVisibility(View.GONE);
			break;
		case 4:
			tv_order_type.setText("长株潭拼车");
			ll_navigation_distance.setVisibility(View.GONE);
			break;
		default:
			break;
		}

		if (navigateDistance < 1 && order.orderType != 4) {
			caculateNavigateDistance(order);
		}
	}

	@Override
	public void setListeners() {

		mImgLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				OrderDetailActivity.this.finish();
			}
		});

		btn_order_operation.setOnClickListener(this);
		iv_call.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (order == null) {
			toast("订单异常，请刷新列表重试");
			return;
		}
		switch (v.getId()) {
		case R.id.btn_order_operation:
			switch (order.orderStatus) {
			case 1:
				if (dialog1 == null) {
					dialog1 = new CommonAlertDialog(this, "确定", "取消", "确定已到达乘客上车地址？", new CommonAlertDialog.OnDialogDismissListener() {
						@Override
						public void onConfirmClicked() {
							arriveStartLocation();
						}

						@Override
						public void onCancelClicked() {

						}
					});
					dialog1.setOwnerActivity(this);
				}
				dialog1.show();
				break;
			case 2:
				if (dialog2 == null) {
					dialog2 = new CommonAlertDialog(this, "确定", "取消", "确定乘客已上车？", new CommonAlertDialog.OnDialogDismissListener() {
						@Override
						public void onConfirmClicked() {
							startTheTrip();
						}

						@Override
						public void onCancelClicked() {

						}
					});
					dialog2.setOwnerActivity(this);
				}
				dialog2.show();
				break;
			case 3:
				if (dialog3 == null) {
					dialog3 = new CommonAlertDialog(this, "确定", "取消", "确定已到达目的地？", new CommonAlertDialog.OnDialogDismissListener() {
						@Override
						public void onConfirmClicked() {
							/**拼车和日租直接结束行程，不需要进行费用确认**/
//							if(order.orderType == OrderType.SHAREING.getValue() || order.orderType == OrderType.DAILY.getValue()){
//								arriveEndLocation(order);
//							}else{
								Intent intent2 = new Intent();
								intent2.setAction(BusConstant.ACTION_STOP_DISTANCE_SERVICE);
								sendBroadcast(intent2);
								
								Intent intent = new Intent(OrderDetailActivity.this, OrderConfirmActivity.class);
								intent.putExtra("order", order);
								startActivity(intent);
								OrderDetailActivity.this.finish();
//							}
						}

						@Override
						public void onCancelClicked() {

						}
					});
					dialog3.setOwnerActivity(this);
				}
				dialog3.show();
				break;
			case 5:
				Intent intent = new Intent(OrderDetailActivity.this, OrderConfirmActivity.class);
				intent.putExtra("order", order);
				startActivity(intent);
				OrderDetailActivity.this.finish();
			default:
				toast("订单状态异常，请退出后重试");
				break;
			}
			break;
		case R.id.iv_call:
			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + order.userPhone));
			startActivity(intent);
			break;
		case R.id.button_right:
			if (initDirs()) {
				initNavi();
			}
			break;
		default:
			break;
		}

	}

	private void arriveStartLocation() {
		// 0 接单、 1 运营中、 2 休息
		if (MyApplication.driverStatus == 1) {
			toast("请先完成服务中的订单");
			return;
		}
		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("orderId", "" + order.orderId);
		http.addBodyParm("groupId", "" + order.groupId);
		http.addBodyParm("driverId", "" + order.driverId);
		ProgressUtil.showProgress(this, "");
		http.send(Url.ready_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				// {"message":null,"order":{"createTime":1449630353000,"endLatitude":40.047862,"remarks":null,"finalPrice":null,"carType":0,"endLongtitude":116.363094,"distance":10000,"endLocation":"北领地c区","userId":4,"driverId":1,"userName":"马杰","userPhone":"13112345678","startLongtitude":116.324178,"driverName":"陈馨(宝马湘A**897)","orderId":130,"startLatitude":40.089919,"orderType":1,"number":1,"driverPhone":"13333333331","perDistance":1.5,"takeTime":11100000,"startLocation":"专家国际公馆","orderStatus":2,"payId":null,"groupId":8881611,"payStatus":null,"estimatePrice":15000},"dirverSize":null,"callStatus":0}
				ProgressUtil.closeProgress();

				try {
					if (object.get("status").equals("0")) {
						object = object.getJSONObject("result");
						if (object != null) {
							if (object.optInt("callStatus", 0) == 10) {
								ToastUtil.showToast("操作失败,有行驶中的订单");
							} else {
								order = new Gson().fromJson(object.getString(("order")), new TypeToken<Order>() {
								}.getType());
								fillViewWithData(order);
								MyOrderFragment.isFresh = true;
							}
						}
					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				toast("" + error);
				ProgressUtil.closeProgress();
			}
		});
	}

	private void startTheTrip() {
		if (MyApplication.driverStatus == 1) {
			toast("请先完成服务中的订单");
			return;
		}
		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("orderId", "" + order.orderId);
		http.addBodyParm("groupId", "" + order.groupId);
		http.addBodyParm("driverId", "" + order.driverId);
		ProgressUtil.showProgress(this, "");
		http.send(Url.start_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				// {"message":null,"order":{"createTime":1449630353000,"endLatitude":40.047862,"remarks":null,"finalPrice":null,"carType":0,"endLongtitude":116.363094,"distance":10000,"endLocation":"北领地c区","userId":4,"driverId":1,"userName":"马杰","userPhone":"13112345678","startLongtitude":116.324178,"driverName":"陈馨(宝马湘A**897)","orderId":130,"startLatitude":40.089919,"orderType":1,"number":1,"driverPhone":"13333333331","perDistance":1.5,"takeTime":11100000,"startLocation":"专家国际公馆","orderStatus":2,"payId":null,"groupId":8881611,"payStatus":null,"estimatePrice":15000},"dirverSize":null,"callStatus":0}
				ProgressUtil.closeProgress();
				try {
					if (object.get("status").equals("0")) {
						object = object.getJSONObject("result");
						if (object != null) {
							order = new Gson().fromJson(object.getString(("order")), new TypeToken<Order>() {
							}.getType());
							fillViewWithData(order);

							MyOrderFragment.isFresh = true;
							MyPreferenceManager.instance().putSharedInfoOfFloat(PreferenceKey.GO_DISTANCE, 0.0f);
							Intent intentService = new Intent(OrderDetailActivity.this, DistanceService.class);
							//intentService.putExtra("order", order);
							startService(intentService);
						}
					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				toast("" + error);
				ProgressUtil.closeProgress();
			}
		});
	}

	private boolean initDirs() {
		mSDCardPath = FileUtils.getSdcardDir();
		if (mSDCardPath == null) {
			return false;
		}
		File f = new File(mSDCardPath, APP_FOLDER_NAME);
		if (!f.exists()) {
			try {
				f.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	String authinfo = null;

	private void initNavi() {
		BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new NaviInitListener() {
			@Override
			public void onAuthResult(int status, String msg) {
				if (0 == status) {
					authinfo = "key校验成功!";
				} else {
					authinfo = "key校验失败, " + msg;
				}
				OrderDetailActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(OrderDetailActivity.this, authinfo, Toast.LENGTH_LONG).show();
					}
				});
			}

			public void initSuccess() {
				Toast.makeText(OrderDetailActivity.this, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
				if (BaiduNaviManager.isNaviInited()) {
					routeplanToNavi(CoordinateType.GCJ02);
				}
			}

			public void initStart() {
				Toast.makeText(OrderDetailActivity.this, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
			}

			public void initFailed() {
				Toast.makeText(OrderDetailActivity.this, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
			}
		}, null);
	}

	private void routeplanToNavi(final CoordinateType coType) {
		// 从当前位置到目的地
		final LocationClient locationClient = new LocationClient(getApplicationContext());
		locationClient.setLocOption(MyLocationClient.getInstance(this).getLocationOption());

		locationClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {
				double latitude = location.getLatitude();
				double longitude = location.getLongitude();
				MyApplication.instance().curLatitude = latitude;
				MyApplication.instance().curLongtitude = longitude;
				locationClient.stop();

				BNRoutePlanNode sNode = null;
				BNRoutePlanNode eNode = null;
				switch (coType) {
				case GCJ02:
					sNode = new BNRoutePlanNode(location.getLongitude(), location.getLatitude(), location.getLocationDescribe(), null, coType);
					eNode = new BNRoutePlanNode(order.endLongtitude, order.endLatitude, order.endLocation, null, coType);
					break;
				default:
					;
				}
				if (sNode != null && eNode != null) {
					List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
					list.add(sNode);
					list.add(eNode);
					BaiduNaviManager.getInstance().launchNavigator(OrderDetailActivity.this, list, 1, true, new DemoRoutePlanListener(sNode));
				}

			}

		});
		locationClient.start();

	}

	public class DemoRoutePlanListener implements RoutePlanListener {

		private BNRoutePlanNode mBNRoutePlanNode = null;

		public DemoRoutePlanListener(BNRoutePlanNode node) {
			mBNRoutePlanNode = node;
		}

		@Override
		public void onJumpToNavigator() {
			/*
			 * 设置途径点以及resetEndNode会回调该接口
			 */

			for (Activity ac : activityList) {

				if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) {

					return;
				}
			}
			Intent intent = new Intent(OrderDetailActivity.this, BDNavGuideActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
			intent.putExtras(bundle);
			startActivity(intent);

		}

		@Override
		public void onRoutePlanFailed() {
			Toast.makeText(OrderDetailActivity.this, "算路失败", Toast.LENGTH_SHORT).show();
		}
	}

	private void caculateNavigateDistance(Order order) {
		RoutePlanSearch routePlanSearch = null;
		if (order != null) {
			routePlanSearch = RoutePlanSearch.newInstance();
			PlanNode startNode = PlanNode.withLocation(new LatLng(order.startLatitude, order.startLongtitude));
			PlanNode endNode = PlanNode.withLocation(new LatLng(order.endLatitude, order.endLongtitude));
			routePlanSearch.setOnGetRoutePlanResultListener(new GetRoutePlanResult(2, mHandler, new LatLng(order.startLatitude, order.startLongtitude), new LatLng(order.endLatitude,
					order.endLongtitude)));
			DrivingRoutePlanOption option = new DrivingRoutePlanOption().from(startNode).to(endNode).policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_TIME_FIRST);
			routePlanSearch.drivingSearch(option);
		}

	}

	public class GetRoutePlanResult implements OnGetRoutePlanResultListener {
		private int id;
		private Handler handler;
		private LatLng mStart;;
		private LatLng mEnd;
		private final String TAG = GetRoutePlanResult.class.getSimpleName();

		public GetRoutePlanResult(int msg, Handler handler, LatLng start, LatLng end) {
			this.id = msg;
			this.handler = handler;
			this.mStart = start;
			this.mEnd = end;
		}

		@Override
		public void onGetDrivingRouteResult(DrivingRouteResult result) {
			if (result != null && result.getRouteLines() != null && result.getRouteLines().size() > 0) {
				if (id == 2) {
					Message msg = handler.obtainMessage();
					msg.what = SET_NAVIGATION_DISTANCE;
					msg.arg1 = (int) Math.ceil(result.getRouteLines().get(0).getDistance() / 1000.f);// 导航距离
					navigateDistance = msg.arg1;
					handler.sendMessage(msg);
				}
			}
		}

		@Override
		public void onGetTransitRouteResult(TransitRouteResult arg0) {

		}

		@Override
		public void onGetWalkingRouteResult(WalkingRouteResult arg0) {

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
